package core.schedulers;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import core.router.Packet;
import eduni.simjava.distributions.Sim_negexp_obj;

public class PacketScheduler {

	private SchedulerKind type;
	private ArrayList<PacketListener> listeners;
	private double meanPacketSize;
	private Sim_negexp_obj exponentialDistribution;
	
	private Timer timer;
	private final int INITIAL_DELAY = 1;

	public PacketScheduler(double meanPacketSize, double meanPacketInterval, 
			SchedulerKind t) {

		this.type = t;
		exponentialDistribution = new Sim_negexp_obj("Time between packets",
				meanPacketInterval);
		this.meanPacketSize = meanPacketSize;
		
		listeners = new ArrayList<PacketListener>();
        timer = new Timer();
        timer.schedule(new RemindTask(), INITIAL_DELAY);

	}

	public void addListener(PacketListener listener) {
		listeners.add(listener);
	}

	public void generatePackage() {
		System.out.println();
		System.out.println("Gerar um pacote do " + type);
		Packet p = new Packet(meanPacketSize);
		System.out.println("Pacote com tamanho " + p.getSize());
		broadcastToListeners(p);
	}

	private void broadcastToListeners(Packet packet) {
		for (PacketListener listener : listeners) {
			listener.onPacketReceiver(packet, type);
		}
	}
	
    class RemindTask extends TimerTask {
        public void run() {
    		generatePackage();
    		double interval = exponentialDistribution.sample();
    		System.out.println("Intervalo entre os pacotes " + interval);
    		timer.schedule(new RemindTask(), (int) interval);
        }
    }
}
